package cn.zqh.minio.service.impl;

import cn.zqh.bean.api.CommonResult;
import cn.zqh.bean.api.ResultCode;
import cn.zqh.minio.service.FileService;
import cn.zqh.minio.utils.MinioUtilS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @Author: zqh
 * @Date: 2022-10-20-9:50
 * @Description: 文件上传实现类$
 */
@Service
public class FileServiceImpl implements FileService {
    
    @Autowired
    private MinioUtilS minioUtilS;
    @Value("${minio.endpoint}")
    private String address;
    @Value("${minio.bucketName}")
    private String bucketName;
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 文件上传
    */
    @Override
    public CommonResult upload(MultipartFile file) {

        List<String> upload = minioUtilS.upload(new MultipartFile[]{file});
        String fileFormat = upload.get(0).substring(upload.get(0).length()-4);
        if (!fileFormat.equals(".jpg")&&!fileFormat.equals(".png")&&!fileFormat.equals(".gif")&&!fileFormat.equals(".mp4")&&!fileFormat.equals(".mp3")){
            minioUtilS.delete(bucketName,upload.get(0));
//            return R.error().data("res","\"文件上传失败，只支持jpg,png,gif,mp4格式\"");
            return CommonResult.failed(ResultCode.THEFILEFORMATNOTCONFORMTOTHEREGULATIONS);

        }
        else {
//            return R.ok().data("res","http://60.205.253.99:9000"+"/"+bucketName+"/"+upload.get(0));
            return CommonResult.success(ResultCode.SUCCESS,"http://43.138.31.196:9000"+"/"+bucketName+"/"+upload.get(0));
        }
    }
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 通过文件名删除文件
    */
    @Override
    public CommonResult delPictureByName(String fileName) {
        String substring = fileName.substring(36, 81);
        minioUtilS.delete(bucketName,substring);
        return CommonResult.success(ResultCode.SUCCESS);
    }
}
